import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/store.js'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css' //这个样式必须引入

Vue.use(Router);
// 简单配置
NProgress.inc(0.2)
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false })

//定义对象与后台返回数据的路由路径对应（自定义路由对象）
const ruleRouter = {
  "about": {
    path: '/about',
    component: () => import('@/commons/About'),
    meta: { isLogin: true },
  },
  "adminshow": {
    path: '/adminshow',
    component: () => import('@/commons/AdminShow'),
    meta: { isLogin: true },
  },
  "last": {
    path: '/last',
    component: () => import('@/commons/Last'),
    meta: { isLogin: true },
  }
}



let router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: () => import('@/view/Login')
    },
    {
      path: '/index',
      redirect: '/home',
      component: () => import('@/view/Index'),
      children: [
        {
          path: '/home',
          component: () => import('@/commons/Home'),
          meta: { isLogin: true },
        },
        // {
        //   path: '/about',
        //   component: () => import('@/commons/About'),
        //   meta: { isLogin: true },
        // },
        // {
        //   path: '/adminshow',
        //   component: () => import('@/commons/AdminShow'),
        //   meta: { isLogin: true },
        // }
      ]
    },

  ]
})
// 路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.meta && to.meta.isLogin) {
    sessionStorage.getItem('token') ? next() : next('/login')
  } else {
    next();
  }
})
router.afterEach(() => {
  NProgress.done();
});


// 动态添加路由
export function initRouter() {
  // 获取路由数组
  const currentRouters = router.options.routes;
  // 获取登录成功后台返回的权限（登录时存在sessionStorage与store中的权限数据）
  const navData = store.state.navData;
  // 遍历权限数据 与ruleRouter（自定义路由对象）对应
  navData.forEach(item => {
    if (item.hasOwnProperty('children')) {
      item.children.forEach(item => {
        // 添加meta是否需要登录
        ruleRouter[item.path].meta.isLogin = true;
        // 添加meta 按钮级权限
        ruleRouter[item.path].meta.permission = item.rights;
        // 添加路由
        currentRouters[2].children.push(ruleRouter[item.path]);
      })
    } else {
      ruleRouter[item.path].meta.isLogin = true;
      ruleRouter[item.path].meta.permission = item.rights;
      currentRouters[2].children.push(ruleRouter[item.path]);
    }
  })
  // sessionStorage.setItem('currentRouters', currentRouters)

  //使用路由
  router.addRoutes(currentRouters)
}

//解决跳转报错
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router;